package cn.edu.lcvc.ebuy_2023rj2.web.action.backstage;


import cn.edu.lcvc.ebuy_2023rj2.model.Admin;
import cn.edu.lcvc.ebuy_2023rj2.model.common.ResponseData;
import cn.edu.lcvc.ebuy_2023rj2.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

//处理后台的登录、注销请求
@RestController
@RequestMapping(value = "/api/backstage")
public class LoginLogoutController {
    //通过spring依赖注入创建对象
    @Autowired
    private AdminService adminService;

    //登录请求
    @PostMapping("/login")
    public ResponseData login(String username, String password, HttpSession session){
        ResponseData responseData=null;
        if (adminService.login(username,password)){//如果密码正确
            session.setAttribute("admin",adminService.getAdminByUsername(username));
            responseData=ResponseData.success();
        }else{//如果密码错误
            responseData=ResponseData.error("登录失败，密码错误");
        }
        return responseData;
    }

    //注销请求
    @GetMapping("/logout")
    public ResponseData logout(HttpSession session){
        session.removeAttribute("admin");
        return ResponseData.success();
    }

    //获取当前的登录账户信息
    @GetMapping("/session")
    public ResponseData session(HttpSession session){
        return ResponseData.success((Admin)session.getAttribute("admin"));
    }
}
